import { getInfo, getUserInfoById, login } from '@/api/user'
import { getToken, removeToken, setToken, setTokenTime } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(), // 获取本地cookie
  userInfo: {}
}
const mutations = {
  setToken(state, payload) {
    state.token = payload
    // 存储到cookie
    setToken(payload)
    // 存当前时间戳
    setTokenTime()
  },
  // 用户信息
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // logout 退出
  logout(state) {
    state.token = null
    removeToken()
    state.userInfo = {}
    // 重置路由规则
    resetRouter()
  }
}
const actions = {
  async login(context, data) {
    const res = await login(data)
    // 存储token到state
    context.commit('setToken', res)
  },
  // 获取用户基本信息信息
  async getUserInfo(context) {
    const res = await getInfo()
    res.roles.points.forEach((item, index) => {
      if (typeof item !== 'string') return
      res.roles.points[index] = item.toLocaleLowerCase()
    })
    // 根据id获取用户详细信息
    const userInfoRes = await getUserInfoById(res.userId)
    // 用户基本信息存储到vuex
    context.commit('setUserInfo', { ...res, ...userInfoRes })
    return res
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

